package xiaopiya.robot.handler.weather;

import java.io.ByteArrayOutputStream;
import java.io.UnsupportedEncodingException;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.params.HttpClientParams;
import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * @author Ray (ayufox@gmail.com)
 * @version 0.1
 */
public class WebXmlWeatherService implements IWeatherService
{
	private final static Log LOG = LogFactory
			.getLog(WebXmlWeatherService.class);

	private final static String WEATCHER_URL = "http://www.webxml.com.cn/WebServices/WeatherWebService.asmx?op=getWeatherbyCityName";

	public String getWeather(String city)
	{
		try
		{
			HttpClientParams clientParams = new HttpClientParams();
			clientParams.setConnectionManagerTimeout(8000);
			clientParams.setSoTimeout(8000);
			HttpClient httpclient = new HttpClient(clientParams);
			PostMethod method = new PostMethod(WEATCHER_URL);
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			IOUtils.copy(WebXmlWeatherService.class
					.getResourceAsStream("webxml_request.xml"), baos);
			String requestBody = new String(baos.toByteArray());
			requestBody = requestBody.replaceAll("\\{cityname\\}", city);
			method.setRequestEntity(new StringRequestEntity(requestBody,
					"application/soap+xml; charset=utf-8", "utf-8"));
			httpclient.executeMethod(method);

			String response = new String(method.getResponseBody(), "utf-8");
			WebXmlWeather weather = new WebXmlWeather(response);
			if (LOG.isInfoEnabled())
			{
				LOG
						.info("find weather[" + weather + "] for city[" + city
								+ "]");
			}
			return weather.toString();
		} catch (UnsupportedEncodingException e)
		{
			if (LOG.isInfoEnabled())
			{
				LOG.info("UnsupportedEncodingException", e);
			}
			return "系统错误";
		} catch (Throwable e)
		{
			if (LOG.isInfoEnabled())
			{
				LOG.info("UnsupportedEncodingException", e);
			}
			return "连接天气预报服务器出错，请重试";
		}
	}

	public static void main(String[] args)
	{
		System.out.println(new WebXmlWeatherService().getWeather("巴黎"));
	}
}
